﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ELab.Message
{
    public class FileMessage
    {
        public FileMessage()
        {
        }

        public FileMessage(byte[] data)
        {
            if (data == null || data.Length < 5 || data[0] != (byte)MessageType.File)
                throw new Exception("Invalidate data bytes of Event message");

            byte[] lengBytes = new byte[] { data[1], data[2], data[3], data[4] };
            int length = BitConverter.ToInt32(lengBytes, 0);

            int index = 5; //start Data of the Event
            var endIndex = index;


            // Gets a value of path
            endIndex += length;
            var altBytes = data.Skip(index).Take(endIndex - index).ToArray();

            FilePath = GetString(altBytes);
            index = endIndex;

            FileData = data.Skip(index).ToArray();
        }

        public MessageType Type
        {
            get { return MessageType.File; }
        }


        public string FilePath { get; set; }

        public byte[] FileData { get; set; }


        public byte[] Data
        {
            get
            {
                var data = new byte[] { (byte)this.Type, 0, 0, 0, 0 };

                // Gets which mouse button was pressed.
                var filePath = GetBytes(FilePath);
                data = data.Append<byte>(filePath);

                //number button click 
                data = data.Append<byte>(FileData);

                //Update length of message
                var bytesLength = BitConverter.GetBytes(filePath.Length);
                bytesLength.CopyTo(data, 1);

                return data;
            }
        }


        private byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        private string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
    }
}
